package org.utahgtug.site.view;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;
import com.google.gdata.data.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: gmdayley
 * Date: 12/28/11
 * Time: 12:58 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/events")
public class EventsController {
    private String CALENDAR_ID = "agtg7nvjqrotrso5q7kcatkn08@group.calendar.google.com";
//    private String CALENDAR_ID = "utah-gtug.org_1udgpi3snlmmmb9u19livfv24o@group.calendar.google.com";


    @Autowired
    Calendar service;

    @RequestMapping("/remove/{eventId}")
    public
    @ResponseBody
    String removeAllEvents(@PathVariable String eventId) throws IOException {
        service.events().delete(CALENDAR_ID, eventId).execute();
        return "success";
    }

    @RequestMapping("/upcoming/{count}")
    public
    @ResponseBody
    List<Event> upcoming(@PathVariable Integer count) throws IOException {
        List<Event> upcomingEvents = new ArrayList<com.google.api.services.calendar.model.Event>();

        DateTime today = new DateTime(new Date());
        System.out.println("today.toString() = " + today.toString());

//        http://javadoc.google-api-java-client.googlecode.com/hg-history/71c8e9b19946f57835aaceee8ed2561c7f76a6f6/apis/calendar/v3/com/google/api/services/calendar/Calendar.Events.List.html
        Events events = service
                .events()
                .list(CALENDAR_ID)
//                .setTimeMin("2011-01-01T00:00:00Z")
                .setTimeMin(today.toString() + "Z")
                .setShowDeleted(false)
                .setSingleEvents(true)
                .setOrderBy("startTime")
                .setMaxResults(count)
                .execute();

        List<Event> items = events.getItems();

        for (com.google.api.services.calendar.model.Event event : items) {
            System.out.println("item.getId() = " + event.getId());
            upcomingEvents.add(event);
        }

        return upcomingEvents;
    }
}
